package framework.ui;

import org.openems.entity.ChoiceEntity;
import org.openems.entity.Entity;
import org.openems.entity.Key;

import framework.DomainService;
import framework.EntityStoreListener;

public class EmsButtonConnector {

	public EmsButtonConnector(final IButton button, final DomainService store, Key key) {
		final Entity entity = (ChoiceEntity)store.getEntity(key);
		button.setText(getNextText(entity));
		button.setOnAction(new IButtonListener() {
			@Override
			public void onClick() {
				try {
					entity.setValueText(button.getText());
					store.putEntity(entity);
				}
				catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		
		store.addEntityStoreListener(new EntityStoreListener() {
			@Override
			public void valueChanged(Entity entity) {
				button.setText(getNextText(entity));
			}			
		}, key);
	}

	private String getNextText(final Entity entity) {
		ChoiceEntity e = (ChoiceEntity)entity;
		int index = e.getIndex();
		if (e.getChoices().size()-1 > index) {
			index++;
		}
		else {
			index = 0;
		}
		return e.getChoices().get(index);
	}

}
